package com.github.benmanes.caffeine.demo.Population;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

public class DemoAuto {
    static System.Logger logger = System.getLogger(DemoAuto.class.getName());

    public static void hello(String[] args) {
        System.out.println("args = " + args);
    }


    public static void main(String... args) throws Exception {
        LoadingCache<String, String> cache = Caffeine.newBuilder().build(new CacheLoader<String, String>() {
            //同步加载数据
            @Nullable
            @Override
            public String load(@NonNull String key) throws Exception {
                System.out.println("loading  key=" + key);
                //e:  从 数据库去获取
                return "value from redis or db for " + key;
            }

            //异步加载数据
            @Nullable
            @Override
            public String reload(@NonNull String key, @NonNull String oldValue) throws Exception {
                System.out.println("reloading  key=" + key);

                //eg:  从 数据库去获取

                return "value from redis or db for " + key;

            }
        });

        String key = "疯狂创客圈";
        String val = cache.get(key);
        System.out.println(val);

        String key1 = "疯狂创客圈1";
        //当key不存在时，会立即创建出对象来返回，val 不会为空
        val = cache.get(key1, k -> {
            System.out.println("key:" + k);
            return "一个高并发 研究社群";
        });
        System.out.println(val);

    }

}
